<template>
  <div class="container">
    <div class="search">
      <el-input v-model="params.name" placeholder="请输入歌手名" clearable></el-input>
      <el-input v-model="params.other" placeholder="模糊查询" clearable disabled title="待完善"></el-input>
      <el-button type="primary" @click="findBySearch">搜索</el-button>
      <el-button type="warning" @click="clearParams">清空</el-button>
      <el-button type="success" @click="addSinger">新增</el-button>
    </div>

    <div class="table">
      <el-table :data="singerData" stripe highlight-current-row style="width: 100%" height="75vh">
        <el-table-column fixed label="序号" prop="id" sortable width="80" align="center"></el-table-column>
        <el-table-column fixed label="歌手" prop="name" width="80"></el-table-column>
        <el-table-column label="性别" prop="sex" width="60">
          <template #default="{ row }">
            <!-- 女：0  男：1 -->
            <el-tag v-if="row.sex === '0'" type="danger">女</el-tag>
            <el-tag v-else-if="row.sex === '1'" type="success">男</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="头像" prop="pic" width="110" align="center">
          <template #default="{ row }">
            <el-image style="width: 70px; height: 70px; border-radius: 50%"
              :src="'http://localhost:8080/api/files/' + row.pic"
              :preview-src-list="['http://localhost:8080/api/files/' + row.pic]"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="出生日期" prop="birth" width="120" align="center"></el-table-column>
        <el-table-column label="地址" prop="address" width="120" align="center"></el-table-column>
        <el-table-column label="介绍" prop="introduction" width="600" align="center">
          <template #default="{ row }">
            <div class="multiline-ellipsis">{{ row.introduction }}</div>
          </template>
        </el-table-column>
        <el-table-column label="点击次数" prop="clicks" sortable width="110" align="center"></el-table-column>
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="{ row }">
            <div style="margin-bottom: 5px">
              <el-button type="primary" size="small" @click="editSinger(row)">编辑</el-button>
              <el-button type="success" size="small" @click="downLoad(row)">下载</el-button>
            </div>
            <div>
              <el-button type="info" size="small" @click="detail(row)">详情</el-button>
              <el-popconfirm title="你确定删除吗？" confirm-button-text="确定" cancel-button-text="取消"
                @confirm="deleteSinger(row)">
                <template #reference>
                  <el-button type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <el-pagination v-model:current-page="params.pageNum" v-model:page-size="params.pageSize"
        :page-sizes="[5, 10, 15, 20]" size="default" layout="total, sizes, prev, pager, next, jumper"
        :total="params.total" @size-change="findBySearch" @current-change="findBySearch" />
    </div>

    <div class="dialog">
      <el-dialog v-model="dialogFormVisible" :title="dialogFormData.id || dialogFormData.id === 0 ? '修改信息' : '添加歌手'"
        width="30%" @close="cancel">
        <el-form :model="dialogFormData">
          <el-form-item prop="username" label="歌手名" label-width="20%">
            <el-input v-model="dialogFormData.name" clearable></el-input>
          </el-form-item>
          <el-form-item prop="sex" label="性别" label-width="20%">
            <el-radio-group v-model="dialogFormData.sex">
              <el-radio value="1">男</el-radio>
              <el-radio value="0">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 头像上传 -->
          <el-form-item label="头像" label-width="20%">
            <el-upload action="http://localhost:8080/api/files/upload" list-type="picture-card" :auto-upload="true"
              :limit="1" :on-success="successUpload" :on-remove="handleRemove" :on-preview="handlePicturePreview"
              :file-list="picList" :class="{ 'none-up': uploadDisabled }">
              <i-ep-plus />
            </el-upload>
          </el-form-item>

          <el-form-item prop="birth" label="出生日期" label-width="20%">
            <el-date-picker v-model="dialogFormData.birth" style="width: 90%" type="date" placeholder="选择日期"
              clearable />
          </el-form-item>
          <el-form-item prop="introduction" label="介绍" label-width="20%">
            <el-input v-model="dialogFormData.introduction" style="width: 90%" type="textarea" rows="3"></el-input>
          </el-form-item>
          <el-form-item prop="address" label="地址" label-width="20%">
            <el-input v-model="dialogFormData.address" style="width: 90%" clearable></el-input>
          </el-form-item>
          <el-form-item prop="clicks" label="点击次数" label-width="20%">
            <el-input v-model="dialogFormData.clicks" style="width: 90%" clearable></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submit"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 头像预览 -->
      <el-dialog v-model="preImgVisible" width="600" align-center>
        <img :src="'http://localhost:8080/api/files/' + dialogFormData.pic" alt="头像预览" style="width: 100%" />
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { singerDeleteApi, singerFindBySearchApi, singerSaveApi } from '@/api/singer'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'

// 搜索框数据
const params = ref({
  name: '',
  other: '',
  total: '',
  pageNum: 1,
  pageSize: 5,
})

// 弹窗数据
const dialogFormData = ref({
  id: '',
  name: '',
  sex: '',
  pic: '',
  birth: '',
  introduction: '',
  address: '',
  clicks: '',
})

// 歌手信息
const singerData = ref()

// 控制弹窗的显示与隐藏
const dialogFormVisible = ref(false)
// 控制图像预览
const preImgVisible = ref(false)

// 上传头像列表
const picList = ref<any>([])

// 上传动态类
const uploadDisabled = ref(false)

onMounted(() => {
  findBySearch()
})

// 搜索
const findBySearch = async () => {
  let res = await singerFindBySearchApi(params.value)
  singerData.value = res.data.list
  params.value.total = res.data.total
}
// 清空
const clearParams = () => {
  params.value = {
    name: '',
    other: '',
    total: '',
    pageNum: 1,
    pageSize: 5,
  }
  findBySearch()
}
// 新增
const addSinger = () => {
  dialogFormVisible.value = true
  uploadDisabled.value = false
  // 清除表单信息
  dialogFormData.value = {
    id: '',
    name: '',
    sex: '',
    pic: '',
    birth: '',
    introduction: '',
    address: '',
    clicks: '',
  }
  // TODO：放在这清除会导致一瞬间的异常
  // // 清除头像文件列表数据
  // picList.value = []
}
// 编辑
const editSinger = (row: any) => {
  picList.value = []
  dialogFormVisible.value = true
  dialogFormData.value = row
  if (row.pic) {
    picList.value.push({ name: row.pic, url: 'http://localhost:8080/api/files/' + row.pic })
  }
  uploadDisabled.value = picList.value.length >= 1
}
// 下载
const downLoad = (row: any) => {
  if (row.pic.includes('|')) {
    location.href = 'http://localhost:8080/api/files/' + row.pic
  } else {
    ElMessage.warning('无可下载资源')
  }
}
// 删除
const deleteSinger = async (row: any) => {
  await singerDeleteApi(row.id)
  findBySearch()
  ElMessage.success('删除成功')
}
// 详情
const detail = (row: any) => {
  window.open('https://cn.bing.com/search?q=' + row.name, '_blank')
}
// 头像上传成功
const successUpload = (res: any, file: any, fileList: any) => {
  // console.log('res',res)
  // console.log('file',file)
  // console.log('fileList',fileList)
  picList.value = fileList
  uploadDisabled.value = picList.value.length >= 1
  dialogFormData.value.pic = res.data
}
// 删除头像
const handleRemove = (file: any, fileList: any) => {
  // console.log('file', file)
  // console.log('fileList', fileList)
  let index = picList.value.findIndex((item: any) => {
    return item.uid === file.uid
  })
  picList.value.splice(index, 1)
  uploadDisabled.value = picList.value.length >= 1
  dialogFormData.value.pic = ''
}
// 预览头像
const handlePicturePreview = (file: any) => {
  // console.log('file', file)
  preImgVisible.value = true
}
// 弹窗确定
const submit = async () => {
  await singerSaveApi(dialogFormData.value)
  ElMessage.success(dialogFormData.value.id ? '修改成功' : '添加成功')
  dialogFormVisible.value = false
  findBySearch()
}
// 弹窗取消
const cancel = () => {
  dialogFormVisible.value = false
  picList.value = []
}
</script>

<style scoped lang="scss">
.container {
  .search {
    display: flex;
    flex-wrap: nowrap;

    .el-input {
      width: 200px;
      margin-right: 10px;
    }
  }

  .table {
    margin: 15px 0;

    // 限制介绍的显示格式
    .multiline-ellipsis {
      display: -webkit-box;
      /* 多行折叠支持 */
      -webkit-line-clamp: 3;
      /* 限制显示的行数 */
      -webkit-box-orient: vertical;
      /* 垂直排列子元素（多行） */
      overflow: hidden;
      /* 超出隐藏 */
      text-overflow: ellipsis;
      /* 超出用省略号 */
      line-height: 20px;
      /* 每行高度（可调） */
      max-height: 60px;
      /* 3行 * line-height */
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
  }

  .dialog {

    .el-input,
    .el-select {
      width: 90%;
    }
  }
}

/* CSS */
.cell {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

// 深度选择器
.none-up ::v-deep(.el-upload--picture-card) {
  display: none;
}
</style>
